/* 系统字典页面 */
<template>
  <zero-vxe-grid v-loading="loading">
    <div slot="aside">
      <TreeSide @sysDeptFun="sysDeptFun"/>
    </div>

    <div slot="header">
      <!--    查询条件-->
      <el-collapse-transition>
        <div v-show="viewModuleOptions.showSearch">
          <vxe-form ref="queryForm" :data="viewModuleOptions.searchForm" title-align="right">
            <vxe-form-item title="用户名称" field="name" :item-render="{}">
              <template #default="{ data }">
                <vxe-input max-length="50" v-model="data.name" showWordCount clearable placeholder="请输入用户名称"/>
              </template>
            </vxe-form-item>

            <vxe-form-item title="用户账号" field="account" :item-render="{}">
              <template #default="{ data }">
                <vxe-input max-length="50" v-model="data.account" showWordCount clearable placeholder="请输入用户账号"/>
              </template>
            </vxe-form-item>
            <vxe-form-item title="手机号码" field="mobile" :item-render="{}">
              <template #default="{ data }">
                <vxe-input max-length="50" v-model="data.mobile" showWordCount clearable placeholder="请输入手机号码"/>
              </template>
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button content="搜索" round @click="searchSubmit" status="primary"/>
              <vxe-button content="重置" round
                          @click="searchResetForm"/>
            </vxe-form-item>
          </vxe-form>
        </div>
      </el-collapse-transition>
    </div>
    <div slot="main">
      <vxe-grid v-bind="viewModuleOptions" :ref="viewModuleOptions.ref" v-on="viewModuleOptions.fns">
        <template #buttons>
          <vxe-button content="新增" status="primary" icon="vxe-icon-add"
                      @click="initDialog({ref:addUpdateDialogRef})"
                      v-hasPermi="['sysUser:add']"/>
          <vxe-button content="批量删除" status="danger" icon="vxe-icon-delete" @click="handleDelete"
                      v-hasPermi="['sysUser:delete']"
                      :disabled="viewModuleOptions.dataListSelections.length <= 0"/>
          <vxe-button content="导出" status="success" icon="vxe-icon-cloud-download"
                      @click="handleExport({ref:importDialogRef,title:'系统用户'})" v-hasPermi="['sysUser:export']"/>
          <vxe-button content="导入" icon="vxe-icon-cloud-upload" v-hasPermi="['sysUser:import']"
                      @click="initDialog({ref:importDialogRef})"/>
        </template>

        <template #tools>
          <vxe-button :title="viewModuleOptions.showSearch ? '隐藏搜索' : '显示搜索'" @click="showOrHideClick"
                      icon="vxe-icon-search" circle/>
          <vxe-button :title="viewModuleOptions.isFullscreen ? '还原' : '全屏'" @click="toggleIsFullscreen"
                      class="tool-btn"
                      :icon="viewModuleOptions.isFullscreen ? 'vxe-icon-minimize' : 'vxe-icon-fullscreen'" circle/>
        </template>
        <template #operation="{ row }">
          <vxe-button mode="text" status="primary" content="修改" v-hasPermi="['sysUser:update']"
                      v-if="row.id !=='1'"
                      @click="initDialog({ref:addUpdateDialogRef,row:row})"></vxe-button>
          <vxe-button mode="text" status="danger" content="删除" v-hasPermi="['sysUser:delete']"
                      v-if="row.id !=='1'"
                      @click="handleDelete(row)"></vxe-button>
          <vxe-button mode="text" status="danger" content="重置密码" v-hasPermi="['sysUser:resetPassword']"
                      v-if="row.id !=='1'"
                      @click="handleResetPwd(row)"></vxe-button>
          <vxe-button mode="text" status="danger" content="分配角色" v-hasPermi="['sysRole:assignRole']"
                      v-if="row.id !=='1'"
                      @click="initDialog({ref:authRoleDialogRef,row:row})"></vxe-button>
        </template>

        <template #status="{ row }">
          <vxe-switch v-model="row.status" open-label="启用" open-value="T" close-label="禁用" close-value="F"
                      v-if="checkPermi(['sysUser:updateStatus'],row)"
                      @change="statusChange(row)"/>
          <dict-tag v-else :options="dict.type.enable_status" :value="row.status"/>
        </template>

        <template #roleVoList="{ row }">
          <span v-for="item in row.roleVoList" :key="item.id">
            <span v-if="item.status === 'T'">[{{ item.name }}]&nbsp;</span>
            <el-tooltip v-else :hide-after="1000" content="该角色已经被禁用" placement="top" class="page-refresh">
              <span style="color: rgb(204, 204, 204); text-decoration: line-through">
                [{{ item.name }}]&nbsp;
              </span>
            </el-tooltip>
          </span>
        </template>
      </vxe-grid>

      <!-- 添加、修改 -->
      <add-update :ref="addUpdateDialogRef"
                  :getDataList="getDataList"
                  :dictType="dict.type"/>

      <!-- 导入、导出 -->
      <ZeroImportExport :ref="importDialogRef"
                        :searchForm="viewModuleOptions.searchForm"
                        :importUrl="viewModuleOptions.importUrl"
                        :importTemplateUrl="viewModuleOptions.importTemplateUrl"
                        :exportUrl="viewModuleOptions.exportUrl"
                        :getDataList="getDataList"/>

      <!-- 角色分配 -->
      <authRole :ref="authRoleDialogRef"
                :getDataList="getDataList"/>
    </div>
  </zero-vxe-grid>
</template>

<script>
import viewModule from '@/mixins/vxe-grid'; // 公共js
import TreeSide from './components/TreeSide.vue'; // 左边树
import {checkPermi} from "@/utils/permission";
import addUpdate from "./components/add-update.vue";
import authRole from "./components/auth-role.vue";

export default {
  name: 'sysUser',
  mixins: [viewModule],
  dicts: ['enable_status', 'sex'],
  components: {addUpdate, TreeSide, authRole},
  data() {
    return {
      addUpdateDialogRef: 'addUpdateDialogRef',
      importDialogRef: 'importDialogRef',
      authRoleDialogRef: 'authRoleDialogRef',
      viewModuleOptions: {
        // activatedIsNeed: false,
        dataUrl: '/sysUser/pageList',
        removeUrl: '/sysUser',
        exportUrl: '/sysUser/export',
        importUrl: '/sysUser/import',
        importTemplateUrl: '/sysUser/importTemplate',
        'checkbox-config': {checkMethod: ({row}) => row.id !== '1'},//禁止操作超级管理员
        //列动态定义。
        columns: [
          {type: 'checkbox', width: 50},
          {field: 'account', title: '用户账号'},
          {field: 'name', title: '用户名称'},
          {field: 'deptName', title: '部门'},
          {field: 'mobile', title: '手机号码', width: 80},
          {field: 'roleVoList', title: '角色列表', resizable: true, slots: {default: 'roleVoList'}},
          {field: 'status', title: '状态', sortable: true, resizable: true, slots: {default: 'status'}, width: 90},
          {field: 'createTime', title: '创建时间'},
          {field: 'newestLoginTime', title: '最新登录时间'},
          {
            title: '操作',
            width: 100,
            slots: {default: 'operation'},
            visible: checkPermi(['sysUser:update', 'sysUser:delete', 'sysRole:assignRole', 'sysUser:resetPassword'])
          }
        ]
      },
    }
  },
  methods: {
    checkPermi(value, row) {
      if (row) {
        return checkPermi(value) && row.id !== '1'
      } else {
        return checkPermi(value)
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入用户"' + row.name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        this.loading = true
        let config = {
          url: "/sysUser/resetPassword",
          method: 'put',
          params: {
            userId: row.id,
            newPassword: value
          }
        }
        this.$axiosAuth(config).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.getDataList()
        }).finally(() => {
          this.loading = false
        });
      }).catch(() => {
      });
    },
    //状态列表中切换
    async statusChange(row) {
      let text = row.status === "T" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"角色吗？')
          .then(() => {
            this.loading = true
            let config = {
              url: '/sysUser/updateStatus',
              method: 'put',
              params: {id: row.id, status: row.status}
            }
            this.$axiosAuth(config)
                .catch(() => {
                  row.status = row.status === "T" ? "F" : "T";
                }).finally(() => {
              this.getDataList();
            });
          }).catch(() => {
      }).finally(() => {
        row.status = row.status === "T" ? "F" : "T";
      });
    },
    sysDeptFun(deptId) {
      this.viewModuleOptions.searchForm.deptId = deptId
      this.getDataList()
    }
  }
}
</script>
